<template>
    <show-modal :title="options.title" :loading="options.loading" width="440px" @cancel="cancel" @submit="submit">
        <a-form ref="formRef" :model="formState" :rules="rules" v-bind="layout">
            <a-form-item label="部门名称" name="name">
                <a-input v-model:value="formState.name" placeholder="请填写部门名称" />
            </a-form-item>
            <a-form-item label="部门编码" name="code">
                <a-input v-model:value="formState.code" :disabled="formState.id ? true : false" placeholder="请填写部门编码" />
            </a-form-item>
            <a-form-item label="所属上级" name="parent_id">
                <a-tree-select style="width: 100%" v-model:value="formState.parent_id"
                    :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }" placeholder="请选择上级组织" allow-clear
                    :fieldNames="replaceFields" :tree-data="list">
                </a-tree-select>
            </a-form-item>
            <a-form-item label="状态" name="status">
                <a-switch v-model:checked="formState.status" :checkedValue="1" checked-children="开" un-checked-children="关" />
            </a-form-item>
        </a-form>
    </show-modal>
</template>
<script setup lang="ts">
import { reactive } from 'vue';
import { rules } from './rules'
import { add, update } from '@/api/system/depart';
import { message } from 'ant-design-vue';
import { useForm } from '@/hooks/use-form/index'
import { IDepart } from '../depart.type';

let props = defineProps({
    info: {
        type: Object,
        default: () => null
    },
    list: {
        type: Array,
        default: () => []
    }
})
let replaceFields = {
    children: 'children',
    label: 'name',
    value: 'id',
}

let emit = defineEmits(['cancel', 'submit']);
// /**基本配置 */
const options = reactive({
    title: '部门信息',
    loading: false
})

/**表单 */
let form = reactive<IDepart>({
    parent_id: undefined,
    name: '',
    code: '',
    status: true,
});

props.info && Object.assign(form, props.info)

const { formRef, layout, formState, showLoading, hideLoading, formValidateFields } = useForm(form)
// 提交
const submit = async () => {
    try {
        let res = await formValidateFields();
        showLoading()
        if (res.id) {
            await update(res);
        } else {
            await add(res);
        }
        message.success('操作成功');
        emit('submit');
    } finally {
        hideLoading()
    }
}
//取消
const cancel = () => {
    emit('cancel')
}
</script>